package com.fxd.service.impl;

import com.fxd.dao.IAccountDao;
import com.fxd.domain.Account;
import com.fxd.service.IAccountService;
import com.fxd.uitls.transactionManager;

import java.util.List;

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

//    private transactionManager txManager;
//
//    public void setTxManager(transactionManager txManager) {
//        this.txManager = txManager;
//    }

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void transfer(String sourceName, String targetName, Float money) {
//        try {
            //1,开启事物
            //txManager.begin();

            //2,执行操作
            //2.1,根据名称查询转出账户
            Account source = accountDao.findAccountByName(sourceName);
            //2.2,根据名称查询转入账号
            Account target = accountDao.findAccountByName(targetName);
            //2.3,转出账户减钱
            source.setMoney(source.getMoney() - money);
            //2.4,转入账号加钱
            target.setMoney((target.getMoney() + money));
            //2.5,更新转出账户
            accountDao.updateAccount(source);

            int i = 1 / 0;

            //2.6,更新转入账号
            accountDao.updateAccount(target);

            //3,提交事物
            //  txManager.commit();
            //4,返回结果
//        } catch (Exception e) {
//            //5,回滚操作
//            // txManager.rollback();
//            e.printStackTrace();
//        } finally {
//            //6,释放连接
//            // txManager.release();
//        }


    }

    @Override
    public Account findByName(String accountName) {
        try {
            //1,开启事物
            //txManager.begin();
            //2,执行操作
            Account a = accountDao.findAccountByName(accountName);
            //3,提交事物
            //txManager.commit();
            //4,返回结果
            return a;
        } catch (Exception e) {
            //5,回滚操作
            //txManager.rollback();
            throw new RuntimeException(e);
        } finally {
            //6,释放连接
            //txManager.release();
        }
    }
}
